﻿using System.Windows.Controls;

using Coding4Fun.Cannon.Phone.Cannon;
using Coding4Fun.Cannon.Phone.Sensor;

namespace Coding4Fun.Cannon.Phone.Controls
{
	public partial class AimView : UserControl
	{
		public AimView()
		{
			InitializeComponent();
		}

		public void StartAccelerometer()
		{
			App.Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
			App.Accelerometer.Start(5);
		}

		public void StopAccelerometer()
		{
			App.Accelerometer.ReadingChanged -= Accelerometer_ReadingChanged;
			App.Accelerometer.Stop();
		}

		void Accelerometer_ReadingChanged(object sender, AccelerometerDataAsyncEventArgs e)
		{
			Dispatcher.BeginInvoke(() => CallService(e));
		}

		private const string AngleFormat = "00.0";
		private const string RawFormat = "0.00";

		private void DisplayReading(AccelerometerData data)
		{
			//Set smaller precision for text value
			uxHorizontalSlider.Value = double.Parse(CannonAim.CurrentPan.ToString(AngleFormat));
			uxVerticalSlider.Value = double.Parse(CannonAim.CurrentTilt.ToString(AngleFormat));

			PositionX.Text = data.X.ToString(RawFormat);
			PositionY.Text = data.Y.ToString(RawFormat);
			PositionZ.Text = data.Z.ToString(RawFormat);
		}

		private void CallService(AccelerometerDataAsyncEventArgs e)
		{
			Logger.WriteLine("AimView Accelerometer Changed");

			var pan = CannonAim.CalculatePan(e.Data.Y);
			var tilt = CannonAim.CalculateTilt(e.Data.Z);

			App.Service.PanAndTilt(pan, tilt);

			//Display and set data
			DisplayReading(e.Data);
		}
	}
}
